package com.banciyuan.bcywebview.biz.circles.smooth.fragment;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.GroupApi;
import com.banciyuan.bcywebview.api.TagApi;
import com.banciyuan.bcywebview.base.view.recycleview.OnResultScrollListener;
import com.banciyuan.bcywebview.biz.circles.smooth.adapter.CircleSmoothTalkAdapter;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.GroupWork;

/**
 * Created by squall on 2016/9/30.
 */

public class CircleSmoothTalkFragment extends CircleBaseSmoothFragment {

    private List<GroupWork> glist = new ArrayList<>();
    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private CircleSmoothTalkAdapter circleSmoothTalkAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View viewroot = inflater.inflate(R.layout.circle_smooth_fragment, null);
        initArgs();
        initProgressbar(viewroot);
        initUi(viewroot);
        initAction();
        return viewroot;
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initArgs() {
        super.initArgs();
    }

    @Override
    protected void initUi(View rootview) {
        recyclerView = (RecyclerView) rootview.findViewById(R.id.recycle);
        swipeRefreshLayout = (SwipeRefreshLayout) rootview.findViewById(R.id.swipe);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(linearLayoutManager);

        swipeRefreshLayout.setProgressViewOffset(false, UIUtils.dip2px(205, getActivity()) + getOffset(), UIUtils.dip2px(280, getActivity()) + getOffset());
        swipeRefreshLayout.setColorSchemeResources(R.color.pink, R.color.pink);
        circleSmoothTalkAdapter = new CircleSmoothTalkAdapter(glist, getActivity(), true, type, name, true);
        recyclerView.setAdapter(circleSmoothTalkAdapter);
    }

    @Override
    protected void initAction() {
        recyclerView.addOnScrollListener(new OnResultScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager ll = (LinearLayoutManager) recyclerView.getLayoutManager();
                if (dy < 0) {
                    if (ll.findFirstVisibleItemPosition() == 0 && ll.getChildAt(ll.findFirstVisibleItemPosition()).getTop() > -UIUtils.dip2px(108, getActivity())) {
                        onFoldScrollListener.onScroll(dy);
                    }
                } else {
                    onFoldScrollListener.onScroll(dy);
                }
            }

            @Override
            public void onTop() {
                onFoldScrollListener.onTop();
            }

            @Override
            public void onBottom() {
                if (!loading && !end_flag) {
                    page++;
                    initData();
                }
            }
        });

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loading = false;
                end_flag = false;
                page = 1;
                initData();
            }
        });
    }

    @Override
    protected void initData() {
        loading = true;
        String url = "";
        if (type.equals(HttpUtils.WORK)) {
            url = HttpUtils.BASE_URL + GroupApi.getListhotcore();
        } else if (type.equals(HttpUtils.TAG)) {
            url = HttpUtils.BASE_URL + TagApi.getDetail();
        }
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.ID, id));
        paramsList.add(new BcyPair(HttpUtils.NAME, name));
        paramsList.add(new BcyPair(HttpUtils.INDEX_P, page + ""));
        paramsList.add(new BcyPair(HttpUtils.TAG_FILTER, "group"));
        Map<String, String> map = HttpUtils.getData(paramsList);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    if (StatusCodeUtils.dealStatusCode(s, getActivity())) {

                        Gson gson = new Gson();
                        JSONObject jsonObject = new JSONObject(s);
                        JSONObject outerData = jsonObject.getJSONObject(HttpUtils.UPLOAD_DATA);
                        String data = outerData.getString("group_data");
                        String count = outerData.getString("count");
                        List<GroupWork> tempList = gson.fromJson(data, new TypeToken<List<GroupWork>>() {
                        }.getType());
                        renderGroup(tempList, count);
                    } else {
                        loading = false;
                        swipeRefreshLayout.setRefreshing(false);
                    }
                } catch (Exception e) {
                    loading = false;
                    swipeRefreshLayout.setRefreshing(false);
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                loading = false;
                swipeRefreshLayout.setRefreshing(false);
            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        queue.add(requestParam);
    }

    private void renderGroup(List<GroupWork> templist, String count) {
        if (page == 1) {
            glist.clear();
        }
        if (templist.isEmpty()) {
            end_flag = true;
        } else {
            if (templist.get(templist.size() - 1).is_end()) {
                end_flag = true;
            }
        }
        glist.addAll(templist);
        if (circleSmoothTalkAdapter == null) {
            circleSmoothTalkAdapter = new CircleSmoothTalkAdapter(glist, getActivity(), false, type, name, true);
            circleSmoothTalkAdapter.setCount(count);
            circleSmoothTalkAdapter.setIs_end(end_flag);
            recyclerView.setAdapter(circleSmoothTalkAdapter);
        } else {
            circleSmoothTalkAdapter.setLoading(false);
            circleSmoothTalkAdapter.setIs_end(end_flag);
            circleSmoothTalkAdapter.setCount(count);
            if (page == 1) {
                circleSmoothTalkAdapter.setHeight(0);
                circleSmoothTalkAdapter.setMax(-1);
                circleSmoothTalkAdapter.notifyDataSetChanged();
            } else {
                circleSmoothTalkAdapter.notifyItemRangeInserted(glist.size() - templist.size() + 2, templist.size());
                circleSmoothTalkAdapter.notifyItemChanged(circleSmoothTalkAdapter.getItemCount() - 1);
            }

        }
        loading = false;
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void getParentHeight(int height) {
        if (!isVisibleToUser) {
            LinearLayoutManager ll = (LinearLayoutManager) recyclerView.getLayoutManager();
            int index = ll.findFirstVisibleItemPosition();
            if (index == 0 || index == -1) {
                ll.scrollToPositionWithOffset(0, height);
            }
        }
    }
}
